package com.tjec.project.system.service.impl;

import com.tjec.common.constant.UserConstants;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.aspectj.lang.annotation.DataScope;
import com.tjec.framework.web.domain.TreeSelectAndChildrenNum;
import com.tjec.project.system.domain.SysDept;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.mapper.SysDeptMapper;
import com.tjec.project.system.service.ISysDeptService;
import com.tjec.project.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author tjec
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    private static final Logger log = LoggerFactory.getLogger(SysDeptServiceImpl.class);

    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        List<SysDept> sysDeptLisst = deptMapper.selectDeptList(dept);
        sysDeptLisst.forEach(item -> {
            convertListView(item);
        });
        return sysDeptLisst;
    }

    /**
     * 转化列表视图
     *
     * @param sysDept
     */
    private void convertListView(SysDept sysDept) {
        convertView(sysDept);

        if (StringUtils.isNotBlank(sysDept.getLeader())) {
            //设置负责人名称
            List<SysUser> leaderSysUser = iSysUserService.getUserByGuids(sysDept.getLeaders());
            List<String> leaderList = leaderSysUser.stream().map(k -> k.getNickName()).collect(Collectors.toList());
            sysDept.setLeadersName(String.join(",", leaderList));
        }
        if (StringUtils.isNotBlank(sysDept.getWhatBusinessLeader())) {
            //设置业务所负责人名称
            List<SysUser> whatBusinessLeaderSysUser = iSysUserService.getUserByGuids(sysDept.getWhatBusinessLeaders());
            List<String> whatBusinessLeaderList = whatBusinessLeaderSysUser.stream().map(k -> k.getNickName()).collect(Collectors.toList());
            sysDept.setWhatBusinessLeadersName(String.join(",", whatBusinessLeaderList));
        }
        if (StringUtils.isNotBlank(sysDept.getDeputyDir()) ) {
            //设置业务分管领导名称
            List<SysUser> deputyDirSysUser = iSysUserService.getUserByGuids(sysDept.getDeputyDirs());
            List<String> deputyDirList = deputyDirSysUser.stream().map(k -> k.getNickName()).collect(Collectors.toList());
            sysDept.setDeputyDirsName(String.join(",", deputyDirList));
        }
        if (StringUtils.isNotBlank(sysDept.getCachetManage()) ) {
            //设置公章管理员名称
            List<SysUser> cachetManageSysUser = iSysUserService.getUserByGuids(sysDept.getCachetManages());
            List<String> cachetManageList = cachetManageSysUser.stream().map(k -> k.getNickName()).collect(Collectors.toList());
            sysDept.setCachetManagesName(String.join(",", cachetManageList));
        }
        if (StringUtils.isNotBlank(sysDept.getTechLeader()) ) {
            //设置所部技术负责人名称
            List<SysUser> techLeaderSysUser = iSysUserService.getUserByGuids(sysDept.getTechLeaders());
            List<String> techLeaderList = techLeaderSysUser.stream().map(k -> k.getNickName()).collect(Collectors.toList());
            sysDept.setTechLeadersName(String.join(",", techLeaderList));
        }
        if (StringUtils.isNotBlank(sysDept.getWhatBusinessTechLeader())) {
            //设置业务所技术负责人名称
            List<SysUser> whatBusinessTechLeaderSysUser = iSysUserService.getUserByGuids(sysDept.getWhatBusinessTechLeaders());
            List<String> whatBusinessTechLeaderList = whatBusinessTechLeaderSysUser.stream().map(k -> k.getNickName()).collect(Collectors.toList());
            sysDept.setWhatBusinessTechLeadersName(String.join(",", whatBusinessTechLeaderList));
        }
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<String> tempList = new ArrayList<String>();
        for (SysDept dept : depts) {
            tempList.add(dept.getGuid());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectAndChildrenNum> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelectAndChildrenNum::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<String> selectDeptListByRoleId(String roleId) {
        List<String> res = deptMapper.selectDeptListByRoleId(roleId);
        return res;
    }

    /**
     * 根据部门ID查询信息
     *
     * @param guid 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(String guid) {
        SysDept sysDept = deptMapper.selectDeptById(guid);
        convertView(sysDept);
        return sysDept;
    }

    /**
     * 转化视图
     *
     * @param sysDept
     */
    private void convertView(SysDept sysDept) {
        String leader = sysDept.getLeader();
        String whatBusinessLeader = sysDept.getWhatBusinessLeader();
        String deputyDir = sysDept.getDeputyDir();
        String cachetManage = sysDept.getCachetManage();
        String techLeader = sysDept.getTechLeader();
        String whatBusinessTechLeader = sysDept.getWhatBusinessTechLeader();

        if (StringUtils.isNotBlank(leader)) {
            sysDept.setLeaders(sysDept.getLeader().split(","));
        }
        if (StringUtils.isNotBlank(whatBusinessLeader)) {
            sysDept.setWhatBusinessLeaders(sysDept.getWhatBusinessLeader().split(","));
        }
        if (StringUtils.isNotBlank(deputyDir)) {
            sysDept.setDeputyDirs(sysDept.getDeputyDir().split(","));
        }
        if (StringUtils.isNotBlank(cachetManage)) {
            sysDept.setCachetManages(sysDept.getCachetManage().split(","));
        }
        if (StringUtils.isNotBlank(techLeader) ) {
            sysDept.setTechLeaders(sysDept.getTechLeader().split(","));
        }
        if (StringUtils.isNotBlank(whatBusinessTechLeader)) {
            sysDept.setWhatBusinessTechLeaders(sysDept.getWhatBusinessTechLeader().split(","));
        }
    }

    /**
     * 是否存在子节点
     *
     * @param guid 部门guid
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(String guid) {
        int result = deptMapper.hasChildByDeptId(guid);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param guid 部门guid
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(String guid) {
        int result = deptMapper.checkDeptExistUser(guid);
        return result > 0 ? true : false;
    }

    @Override
    public boolean checkProjectExistExecuteDept(String guid) {
        int result = deptMapper.checkProjectExistExecuteDept(guid);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        String guid = StringUtils.isNull(dept.getGuid()) ? "-1" : dept.getGuid();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName());
        if (StringUtils.isNotNull(info) && !guid.equals(info.getGuid())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        /*SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());*/
        convertDept(dept);
        String leader = dept.getLeader();
        log.info("部级审批人人员guid==="+leader);
        if (StringUtils.isNotEmpty(leader)) {
            // 根据guid查询部级审批人员工编号jobNo
            String jobNo = iSysUserService.selectUserJobNoByGuid(leader);
            log.info("部级审批人员工编号jobNo==="+jobNo);
            dept.setLeaderNo(jobNo);
        }
        String whatBusinessLeader = dept.getWhatBusinessLeader();
        log.info("所级审批人人员guid==="+whatBusinessLeader);
        if (StringUtils.isNotEmpty(whatBusinessLeader)) {
            // 根据guid查询所级审批人员工编号jobNo
            String jobNo = iSysUserService.selectUserJobNoByGuid(whatBusinessLeader);
            log.info("所级审批人员工编号jobNo==="+jobNo);
            dept.setWhatBusinessLeaderNo(jobNo);
        }
        return deptMapper.insertDept(dept);
    }

    /**
     * 转化部门
     *
     * @param dept
     */
    private void convertDept(SysDept dept) {
        if (null != dept.getLeaders()) {
            dept.setLeader(StringUtils.join(dept.getLeaders(), ","));
        }
        if (null != dept.getWhatBusinessLeaders()) {
            dept.setWhatBusinessLeader(StringUtils.join(dept.getWhatBusinessLeaders(), ","));
        }
        if (null != dept.getDeputyDirs()) {
            dept.setDeputyDir(StringUtils.join(dept.getDeputyDirs(), ","));
        }
        if (null != dept.getCachetManages()) {
            dept.setCachetManage(StringUtils.join(dept.getCachetManages(), ","));
        }
        if (null != dept.getTechLeaders()) {
            dept.setTechLeader(StringUtils.join(dept.getTechLeaders(), ","));
        }
        if (null != dept.getWhatBusinessTechLeaders()) {
            dept.setWhatBusinessTechLeader(StringUtils.join(dept.getWhatBusinessTechLeaders(), ","));
        }
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getGuid());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getGuid();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getGuid(), newAncestors, oldAncestors);
        }
        convertDept(dept);
        String leader = dept.getLeader();
        log.info("部级审批人人员guid==="+leader);
        if (StringUtils.isNotEmpty(leader)) {
            // 根据guid查询部级审批人员工编号jobNo
            String jobNo = iSysUserService.selectUserJobNoByGuid(leader);
            log.info("部级审批人员工编号jobNo==="+jobNo);
            dept.setLeaderNo(jobNo);

        }
        String whatBusinessLeader = dept.getWhatBusinessLeader();
        log.info("所级审批人人员guid==="+whatBusinessLeader);
        if (StringUtils.isNotEmpty(whatBusinessLeader)) {
            // 根据guid查询所级审批人员工编号jobNo
            String jobNo = iSysUserService.selectUserJobNoByGuid(whatBusinessLeader);
            log.info("所级审批人员工编号jobNo==="+jobNo);
            dept.setWhatBusinessLeaderNo(jobNo);
        }
        int result = deptMapper.updateDept(dept);
        /*if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }*/
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getGuid());
        dept.setUpdateBy(updateBy);
        String ancestors = dept.getAncestors();
        if (StringUtils.isBlank(ancestors)) {
            String[] ancestorss = ancestors.split(",");
            deptMapper.updateDeptStatus(dept, ancestorss);
        }
    }

    /**
     * 修改子元素关系
     *
     * @param guid         被修改的部门guid
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(String guid, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(guid);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param guids 部门guids
     * @return 结果
     */
    @Override
    public int deleteDeptById(String[]  guids) {
        return deptMapper.deleteDeptById(guids);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysDept> it = childList.iterator();
                while (it.hasNext()) {
                    SysDept n = (SysDept) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && t.getGuid().equals(n.getParentId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    @Override
    public List<String> selectDeptIds(SysDept dept) {
        // TODO Auto-generated method stub
        return deptMapper.selectDeptIds(dept);
    }
}
